
from rest_framework import serializers

from goods.models import SKUImage, SKU


class ImageSerializer(serializers.ModelSerializer):
    # 返回图片关联的sku的id值
    sku = serializers.PrimaryKeyRelatedField(read_only=True)
    sku_id = serializers.IntegerField()

    class Meta:
        model = SKUImage
        fields = '__all__'

    # def create(self, validated_data):
    #     print(validated_data)
    #     # 创建FastDFS连接对象
    #     client = Fdfs_client(settings.FDFS_BASE_CONF_PATH)
    #     # 获取前端传递的image文件
    #     request = self.context['request']
    #     file = request.FILES.get('image')
    #
    #     # 上传图片到fastDFS
    #     res = client.upload_by_buffer(file.read())
    #     # 判断是否上传成功
    #     if res['Status'] != 'Upload successed.':
    #         raise serializers.ValidationError({'error': '上传失败'})
    #     # 获取上传后的路径
    #     image_url = res['Remote file_id']
    #     # 获取sku_id
    #     sku_id = validated_data['sku_id']
    #     sku = SKU.objects.get(id=sku_id)
    #     # 保存图片
    #     img = SKUImage.objects.create(sku=sku, image=image_url)
    #     print(img)
    #     return img
    # def create(self, validated_data):
    #     ModelClass = self.Meta.model
    #     instance = ModelClass._default_manager.create(**validated_data)
    #     # 异步生成详情页静态页面
    #     generate_static_sku_detail_html.delay(instance.sku_id)
    #     return instance


class SKUSerializer(serializers.ModelSerializer):
    class Meta:
        model = SKU
        fields = ('id', 'name')
